package com.zzyl.nursing.service.impl;

import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataQueryDto;
import com.zzyl.nursing.dto.ElderDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author syl
 * @date 2025-05-30
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private ElderMapper  elderMapper;

    @Autowired
    private BedMapper  bedMapper;

    @Autowired
    private RoomMapper  roomMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceDataListMapper deviceDataListMapper;
    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private TokenService tokenService;  //这是zzyl-framework模块中的

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        String code = dto.getCode();
        String phoneCode = dto.getPhoneCode();

        // 调用微信接口返回openid
        String openid = wechatService.getOpenid(code);

        // 根据openid查询客户信息
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);

        String phone = wechatService.getPhone(phoneCode); //这里要注意获取手机号用的是phoneCode
        if(familyMember==null){
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            //从DEFAULT_NICKNAME_PREFIX随机挑选一个 + 手机号的后四位 0-8
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()))+phone.substring(7));
            familyMember.setOpenId(openid);
            familyMemberMapper.insert(familyMember);
        }else{
            // 这个用户是否修改过手机号
            if (!StrUtil.equals(familyMember.getPhone(),phone)) {
                familyMember.setPhone(phone);
            }
            familyMemberMapper.updateById(familyMember);

        }
        // 根据用户ID和昵称生成Jwt的token
        Map<String, Object> map = new HashMap();
        map.put("id", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map); //这里注意把tokenService.createToken改成public

        LoginVo  loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Override
    public void bind(ElderDto elderDto) {
        //通过elderDto中的数据当作条件来查询老人
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCard());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder==null){
            throw new RuntimeException("没有该老人");
        }
        if(elder.getStatus()==1){
            familyMemberElder.setElderId(elder.getId());
            familyMemberElder.setMemberId(UserThreadLocal.getUserId());
            familyMemberElder.setRemark(elderDto.getRemark());
            familyMemberElderMapper.insert(familyMemberElder);
        }



    }

    @Override
    public List<ElderVo> listByPage() {
        Long userId = UserThreadLocal.getUserId();
        LambdaQueryWrapper<FamilyMemberElder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMemberElder::getMemberId,userId);
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(queryWrapper);
        List<ElderVo> elderVos = new ArrayList<>();
        if (CollUtil.isNotEmpty(familyMemberElders)) {
            familyMemberElders.forEach(v -> {
                ElderVo elderVo = new ElderVo();
                elderVo.setMid(v.getId());
                elderVo.setElderId(v.getElderId().toString());
                elderVo.setName(elderMapper.selectById(v.getElderId()).getName());
                elderVo.setImage(elderMapper.selectById(v.getElderId()).getImage());
                elderVo.setBedNumber(elderMapper.selectById(v.getElderId()).getBedNumber());
//                elderMapper.selectById(v.getElderId()).getBedId();
//                bedMapper.selectBedById(elderMapper.selectById(v.getElderId()).getBedId()).getRoomId();
//                roomMapper.selectRoomById(bedMapper.selectBedById(elderMapper.selectById(v.getElderId()).getBedId()).getRoomId()).getTypeName();
                elderVo.setTypeName(roomMapper.selectRoomById(bedMapper.selectBedById(elderMapper.selectById(v.getElderId()).getBedId()).getRoomId()).getTypeName());
                LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Device::getLocationType,0);
                List<Device> devices = deviceMapper.selectList(queryWrapper1);
                if (CollUtil.isNotEmpty(devices)){
                    devices = devices.stream().filter(x -> x.getBindingLocation().equals(elderVo.getElderId())).collect(Collectors.toList());
                }
                if (CollUtil.isNotEmpty(devices)){
                    elderVo.setIotId(devices.get(0).getIotId());
                    elderVo.setDeviceName(devices.get(0).getDeviceName());
                    elderVo.setProductKey(devices.get(0).getProductKey());
                }

                elderVos.add(elderVo);


            });
        }
        return elderVos;
    }

    @Override
    public List<FamilyElderRelationVo> elderlist() {
        //获取登陆人id
        Long userId = UserThreadLocal.getUserId();
        LambdaQueryWrapper<FamilyMemberElder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMemberElder::getMemberId,userId);
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(queryWrapper);
        List<FamilyElderRelationVo> familyElderRelationVos = new ArrayList<>();
        if (CollUtil.isNotEmpty(familyMemberElders)) {
            familyMemberElders.forEach(v -> {
                FamilyElderRelationVo  familyElderRelationVo = new FamilyElderRelationVo();
                familyElderRelationVo.setId(v.getId());
                familyElderRelationVo.setElderId(v.getElderId());
                familyElderRelationVo.setElderName(elderMapper.selectById(v.getElderId()).getName());
                familyElderRelationVo.setFamilyMemberId(v.getMemberId());
                familyElderRelationVos.add(familyElderRelationVo);
            });
        }
        return familyElderRelationVos;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceData::getIotId,iotId);
        queryWrapper.orderByDesc(DeviceData::getAlarmTime);
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(deviceDataList)) {
            return deviceDataList.stream().map(deviceData -> {
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setValue(deviceData.getDataValue());
                deviceDataVo.setEventTime(deviceData.getAlarmTime());
                deviceDataVo.setFunctionId(deviceData.getFunctionId());
                return deviceDataVo;
            }).collect(Collectors.toList());
        }
        return null;


    }

    @Override
    public List<DeviceDataListVo> queryDeviceDataListByDay(DeviceDataQueryDto queryDto) {
        Date endTime = new Date(queryDto.getEndTime());
        Date starTime = new Date(queryDto.getStartTime());
        List<DeviceDataList> dataList = deviceDataListMapper.selectByTime(queryDto.getIotId(), starTime, endTime);
        return convertToVoList(dataList, "HH:mm", DeviceDataList::getDateTime);
    }

    @Override
    public List<DeviceDataListVo> queryDeviceDataListByWeek(DeviceDataQueryDto queryDto) {
        Date endTime = new Date(queryDto.getEndTime());
        Date starTime = new Date(queryDto.getStartTime());
        List<DeviceDataList> dataList = deviceDataListMapper.selectByDay(queryDto.getIotId(), starTime, endTime);
        return convertToVoList(dataList, "MM-dd", DeviceDataList::getDay);
    }

    private List<DeviceDataListVo> convertToVoList(List<DeviceDataList> dataList, String pattern, Function<DeviceDataList, TemporalAccessor> timeExtractor) {
        List<DeviceDataListVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(dataList)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            for (DeviceDataList item : dataList) {
                DeviceDataListVo vo = new DeviceDataListVo();
                vo.setDateTime(formatter.format(timeExtractor.apply(item)));
                vo.setDataValue(Double.valueOf(String.format("%.2f", item.getDataValue())));
                voList.add(vo);
            }
        }
        return voList;
    }

    @Override
    public void deleteById(Long id) {
        //判断id是否正常
        if (ObjUtil.isNull(id) || id <= 0){
            throw new BaseException("参数异常");
        }

        FamilyMemberElder familyMemberElder = familyMemberElderMapper.selectById(id);
        if (ObjUtil.isNull(familyMemberElder)){
            throw new BaseException("查询异常");
        }

        //删除
        familyMemberElderMapper.deleteById(id);
    }





    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

}
